﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.IO;

#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif

public class PostProcess : MonoBehaviour {

	[PostProcessBuildAttribute(1)]
	public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) {

		#if UNITY_IOS
		// 初始化
		var projectPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj";
		PBXProject pbxProject = new PBXProject();
		pbxProject.ReadFromFile(projectPath);
		string targetGuid = pbxProject.TargetGuidByName("Unity-iPhone");

//		// 添加flag
//		pbxProject.AddBuildProperty(targetGuid, "OTHER_LDFLAGS", "-ObjC");
//		// 关闭Bitcode
//		pbxProject.SetBuildProperty(targetGuid, "ENABLE_BITCODE", "NO");

		// 添加framwrok (this time is for TalkingData)
		pbxProject.AddFrameworkToProject(targetGuid, "Security.framework", false);
		pbxProject.AddFrameworkToProject(targetGuid, "CoreTelephony.framework", false);
		pbxProject.AddFrameworkToProject(targetGuid, "SystemConfiguration.framework", false);
		pbxProject.AddFrameworkToProject(targetGuid, "ImageIO.framework", false);
		pbxProject.AddFrameworkToProject(targetGuid, "CoreData.framework", false);
		pbxProject.AddFrameworkToProject(targetGuid, "CoreMotion.framework", false);
		pbxProject.AddFrameworkToProject(targetGuid, "AdSupport.framework", false);

		//添加lib
		AddLibToProject(pbxProject, targetGuid, "libc++.tbd");
		AddLibToProject(pbxProject, targetGuid, "libz.tbd");

		// 应用修改
		File.WriteAllText(projectPath, pbxProject.WriteToString());

		#endif
	}

	#if UNITY_IOS
	static void AddLibToProject(PBXProject inst, string targetGuid, string lib)
	{
		string fileGuid = inst.AddFile("usr/lib/" + lib, "Frameworks/" + lib, PBXSourceTree.Sdk);
		inst.AddFileToBuild(targetGuid, fileGuid);
	}
	#endif
}
